/*
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/1/22 14:15
@File     : requests.go
@Project  : gohub
@Desc     :
*/
package requests

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/thedevsaddam/govalidator"
	"gohub/pkg/response"
)

// ValidatorFunc 验证函数类型
type ValidatorFunc func(any, *gin.Context) map[string][]string

func Validate(c *gin.Context, obj any, handle ValidatorFunc) bool {

	//解析请求
	if err := c.ShouldBind(obj); err != nil {
		//解析失败返回错误
		response.BadRequest(c, err, "请求解析错误，请确认请求格式是否正确。上传文件请使用 multipart 标头，参数请使用 JSON 格式。")
		fmt.Println("打印错误信息：", err.Error())
		//出错终端后续处理行为
		return false
	}
	//表单验证
	errs := handle(obj, c)
	if len(errs) > 0 {
		response.ValidationError(c, errs)
		return false
	}
	return true
}

func validate(data any, rules govalidator.MapData, messages govalidator.MapData) map[string][]string {
	//配置初始化
	opts := govalidator.Options{Data: data, Rules: rules, Messages: messages, TagIdentifier: "valid"}
	//开始表单验证
	return govalidator.New(opts).ValidateStruct()
}

func validateFile(c *gin.Context, data any, rules govalidator.MapData, messages govalidator.MapData) map[string][]string {
	opts := govalidator.Options{
		Request:       c.Request,
		Rules:         rules,
		Messages:      messages,
		TagIdentifier: "valid",
	}
	//调用govalidator的Validate方法来验证文件
	return govalidator.New(opts).Validate()
}
